/**
 * fileName: CS_YLES_Import_item_barcode_CSV
 * @NApiVersion 2.1
 * @NScriptType ClientScript
 */


//issue:I63Q59
//添加校验进度条
import {EntryPoints} from 'N/types'
import search = require('N/search')
import record = require('N/record')
import url = require('N/url')
import crd = require('N/currentRecord')
import {addScreenDisabled, exportMyCSV, initCheckCSVProgress} from "../tools/YLES_CLIENT_TOOL";
import {CustomRecordType} from "../tools/YLES_RELATED_RECORDTYPE";

const slid = 'info_list';

export function pageInit(cxt: EntryPoints.Client.pageInitContext) {
    const rec = cxt.currentRecord;

    //判断是否启动校验进度条
    if ( jQuery('#check_csv_progress').length > 0){
        try {
            initCheckCSVProgress();
        }catch (e) {
            console.log('启动进度条失败',e);
        }
    }
    // jQuery("#progress_fs").hide();
    // var runtime = require("N/runtime");
    // var crd = require("N/currentRecord");
}

//saveRecord
export function saveRecord(cxt: EntryPoints.Client.saveRecordContext) {
    const rec = cxt.currentRecord;
    //校验程序进程
    let ckSts = checkImportProcess(rec);
    if (!ckSts) return false;

    return true;
}

/**
 * 校验CSV
 */
export function validateCSV() {
    const cur_rec = crd.get();
    const filename = cur_rec.getValue({fieldId: 'upload_file'}) as string;
    console.log('filename', filename);
    if (/.*\.csv/.test(filename)) {
        cur_rec.setValue({fieldId: 'submit_operate', value: 'validate'});

        addScreenDisabled();
        clickSubmit();
    } else {
        alert('Please upload csv file.');
        cur_rec.setValue({fieldId: 'upload_file', value: ''});
    }
}

function clickSubmit() {
    jQuery('#submitter').click();
}


//提交执行更新逻辑
export function updateCSV() {
    const cur_rec = crd.get();
    cur_rec.setValue({fieldId: 'submit_operate', value: 'import'});
    clickSubmit();
}


//执行下载
export function exportCSV() {
    return exportMyCSV();
}


//校验导入程序执行状态
function checkImportProcess(rec: record.ClientCurrentRecord) {
    let rtn = true;
    const Search = search.create({
        type: CustomRecordType().IMPORT_ITEM_BARCODE_LOG,
        filters: [
            ['custrecord_yles_status', 'anyof', ['3']], 'and',
            ['custrecord_yles_operate', 'doesnotcontain', 'validate'], 'and',
            ['custrecord_yles_operate', 'isnotempty', ''], 'and',
            ['isinactive', 'anyof', false]
        ],
        columns: [
            {name: 'internalid'},
            {name: 'internalid'},
            {name: 'custrecord_yles_user'},
            {name: 'created'},
        ]
    })

    Search.run().each(res => {
        rtn = false;
        alert(`Warning!\n 
            There are plans to generate， \n
            the operator is ${res.getText(Search.columns[2])} \n 
            time is ${res.getValue(Search.columns[3])} .`);
        return false;
    });

    return rtn;
}

//刷新界面
export function refresh() {
    window.onbeforeunload = null;
    window.location.reload();
}

export function historyImport() {
    const targetUrl = url.resolveScript({
        scriptId: 'customscript_yles_import_csv_history_sl',
        deploymentId: 'customdeploy_yles_import_csv_history_sl'
    });
    window.open(targetUrl)

}